package serv

import (
	"gorm.io/gorm"
	"server/internal/app/model"
	"server/internal/database"
)

var Area = new(area)

type area struct {
	model.Area
	Children []area `json:"children,omitempty" gorm:"-"`
}

// List 树状图
func (a area) List(pid int) []area {
	Db := database.DB
	var menus []area

	Db.Model(&menus).Where("pid=?", pid).Find(&menus)
	if len(menus) == 0 {
		return nil
	}

	var list []area
	for _, v := range menus {
		v.Children = a.List(v.ID)
		list = append(list, v)
	}

	return list
}

// Read 单条
func (a area) Read(id any) (*gorm.DB, area) {
	Db := database.DB
	detail := area{}
	Db.Model(&a).Where("id =?", id).First(&detail)

	return Db, detail

}

// Create 新增
func (a area) Create(data model.Area) *gorm.DB {
	Db := database.DB

	Db = Db.Model(&data).Create(&data)

	//a.GenerateQrcode(a.ID)

	return Db
}

// Update 编辑
func (a area) Update(data model.Area) *gorm.DB {
	Db := database.DB

	//a.GenerateQrcode(a.ID)

	return Db.Save(&data)

}

// Delete 删除
func (a area) Delete(ids []int) *gorm.DB {
	Db := database.DB

	return Db.Delete(&a, ids)

}

type areaSelect struct {
	Value    int          `json:"value"`
	Label    string       `json:"label"`
	Children []areaSelect `json:"children,omitempty"`
}

func (a area) GetareaIds(pid int, Ids []int) []int {
	Db := database.DB
	var menus []area

	Db.Model(&menus).Select("id,pid").Where("pid=?", pid).Find(&menus)

	if len(menus) == 0 {
		return Ids
	}
	if len(Ids) == 0 {
		Ids = append(Ids, pid)
	}
	for _, v := range menus {
		Ids = append(Ids, v.ID)
		Ids = a.GetareaIds(v.ID, Ids)
	}

	return Ids
}

func (area) GetAreaName(id int) string {

	Db := database.DB
	a := area{}
	Db.Model(&a).Where("id=?", id).Find(&a)
	name := a.Name
	pid := a.Pid
	if pid > 0 {
		for {
			a = area{}
			Db.Model(&a).Where("id=?", pid).Find(&a)
			if a.ID > 0 {
				name = a.Name + "-" + name
			}
			if a.Pid == 0 {
				break
			}
			pid = a.Pid
		}
	}

	return name
}

// GetSelectGradually 远程下拉 逐级查看
func (a area) GetSelectGradually(pid int) []area {
	Db := database.DB
	var menus []area

	Db.Table("tissue").Where("pid=? and level<=?", pid, 4).Find(&menus)

	return menus
}

// Select 远程下拉
func (a area) Select(pid int) []tissueSelect {
	Db := database.DB

	var menus []tissue

	Db.Model(&menus).Where("pid=? and level<=?", pid, 4).Find(&menus)

	var list []tissueSelect

	if len(menus) == 0 {
		return nil
	}
	for _, v := range menus {
		var count int64
		Db.Table("tissue").Where("pid=?", v.ID).Count(&count)
		IsLeaf := false
		if count > 0 {
			IsLeaf = true
		}
		list = append(list, tissueSelect{
			Value:  v.ID,
			Label:  v.Name,
			IsLeaf: IsLeaf,
			//Children: a.Select(v.ID),
		})
	}

	return list
}
